package com.getpebble.android.framework.notification.gmail;

import java.io.IOException;
import myjavax.security.auth.callback.Callback;
import myjavax.security.auth.callback.CallbackHandler;
import myjavax.security.auth.callback.NameCallback;
import myjavax.security.auth.callback.UnsupportedCallbackException;
import myjavax.security.sasl.SaslClient;
import myjavax.security.sasl.SaslException;

class OAuth2SaslClient implements SaslClient {
    private final CallbackHandler callbackHandler;
    private boolean isComplete = false;
    private final String oauthToken;

    public OAuth2SaslClient(String oauthToken, CallbackHandler callbackHandler) {
        this.oauthToken = oauthToken;
        this.callbackHandler = callbackHandler;
    }

    public String getMechanismName() {
        return "XOAUTH2";
    }

    public boolean hasInitialResponse() {
        return true;
    }

    public byte[] evaluateChallenge(byte[] challenge) throws SaslException {
        if (this.isComplete) {
            return new byte[0];
        }
        NameCallback nameCallback = new NameCallback("Enter name");
        try {
            this.callbackHandler.handle(new Callback[]{nameCallback});
            byte[] response = String.format("user=%s\u0001auth=Bearer %s\u0001\u0001", new Object[]{nameCallback.getName(), this.oauthToken}).getBytes();
            this.isComplete = true;
            return response;
        } catch (UnsupportedCallbackException e) {
            throw new SaslException("Unsupported callback: " + e);
        } catch (IOException e2) {
            throw new SaslException("Failed to execute callback: " + e2);
        }
    }

    public boolean isComplete() {
        return this.isComplete;
    }

    public byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException {
        throw new IllegalStateException();
    }

    public byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException {
        throw new IllegalStateException();
    }

    public Object getNegotiatedProperty(String propName) {
        if (isComplete()) {
            return null;
        }
        throw new IllegalStateException();
    }

    public void dispose() throws SaslException {
    }
}
